<template>
  <div class="pagination">
    <button @click="prevPage" :disabled="currentPage <= 1">
      <u-icon name="play-left-fill" :color="currentPage <= 1 ? '#ccc' : ''"></u-icon>
    </button>
    <!-- 回撤事件 -->
    <!-- <input type="number" v-model.number="currentPage" @keyup.enter="gotoPage" min="1" :max="totalPages"> -->
    <!-- 失去焦点事件 -->
    <input type="number" v-model.number="currentPageInput" @blur="gotoPage" min="1" :max="totalPages">
    <span> 共 {{ totalPages }} 页</span>
    <button @click="nextPage" :disabled="currentPage >= totalPages">
      <u-icon name="play-right-fill" :color="currentPage >= totalPages ? '#ccc' : ''"></u-icon>
    </button>
  </div>
</template>

<script>
export default {
  props: {
    total: {
      type: Number,
      required: true
    },
    pageSize: {
      type: Number,
      default: 20 // 默认每页显示10条数据
    },
    pageIndex: {
      type: Number,
      default: 1
    },
  },
  data() {
    return {
      currentPage: this.pageIndex,
      currentPageInput: this.pageIndex
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.total / this.pageSize);
    }
  },
  watch: {
    pageIndex(newVal) {
      this.currentPage = newVal;
      this.currentPageInput = newVal;
    }
  },
  methods: {
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.currentPageInput = this.currentPage
        this.$emit('prevPage', this.currentPageInput)
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.currentPageInput = this.currentPage
        this.$emit('nextPage', this.currentPageInput)
      }
    },
    gotoPage() {
      if (this.currentPageInput >= 1 && this.currentPageInput <= this.totalPages) {
        this.currentPage = this.currentPageInput;
        this.$emit('jumpPage', this.currentPageInput)
      } else {
        this.currentPageInput = this.currentPage;
        this.$emit('jumpPage', this.currentPageInput)
      }
    }
  }
};
</script>

<style scoped>
.pagination {
  display: flex;
  align-items: center;
}

button {
  margin: 0 5px;
  padding: 5px 10px;
  border: 1px solid #ccc;
  border-radius: 3px;
  cursor: pointer;
}

input {
  width: 50px;
  padding: 3px 5px;
  text-align: center;
  border: 1rpx solid #ccc;
}
</style>
